package com.lyf.controll;

import com.lyf.utils.CrossRegion;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@WebServlet("/download")
public class DownloadControll extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, UnsupportedEncodingException {
        //解决跨域
//        CrossRegion.setCross(response);
//        request.setCharacterEncoding("utf-8");
        //1.获取下载链接的fileName
        String fileName = request.getParameter("filename");
        System.out.println(fileName+".......");
        //2.设置响应头
        response.setHeader("content-disposition","attachment;filename=" + fileName);

        //3.下载文件
        File file = new File("D:\\粤嵌Java\\第二阶段\\vue-demo\\vue3_mlsd\\src\\assets");
        try(InputStream is = new FileInputStream(file+File.separator+fileName);
            OutputStream os = response.getOutputStream();
        ){
            int len = 0;
            byte[] b = new byte[1024];
            //循环读写
            while((len = is.read(b)) >0){
                os.write(b,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
